import sys

class Msg:
	MsgDict = {}
	insertSql = "insert into threads values('%s', '%s', %i)"
	inserts = 0

	@classmethod
	def get(cls, id):
		if not cls.MsgDict.has_key(id):
			cls.MsgDict[id] = Msg(id)
		return cls.MsgDict[id]

	def __init__(self, id):
		self.id = id
		self.MsgDict[id] = self
		self.responses = []

	def addResponse(self, msg):
		self.responses.append(msg)

	def commit(self, db, msg, length):
		if msg != self:
			db.query(Msg.insertSql % (msg.id, self.id, length))
			Msg.inserts += 1
			if Msg.inserts % 1000 == 0:
				print "%i inserts so far" % Msg.inserts
		for response in self.responses:
			response.commit(db, msg, length+1)
		

def calcThreads(db, log):
    sql = "select messageid, referenceid from messages"
    log.write("beginning tclosure")
    for msgId, refId in db.query(sql).getresult():
    	if refId:
		    Msg.get(refId).addResponse(Msg.get(msgId))

    print "writing relations to table"
    for msg in Msg.MsgDict.values():
	    msg.commit(db, msg, 0)

    log.write("done with tclosure")
    print "There are %i msg objects" % len(Msg.MsgDict)
    print "There were %i inserts" % Msg.inserts
